<template>
  <div class="app-container">
    <el-form inline label-width="68px">
      <el-form-item label="预约时间">
        <el-date-picker
          :value="reservationTime"
          type="daterange"
          :editable="false"
          :clearable="false"
          :picker-options="pickerOptions"
          format="yyyy-MM-dd HH:mm"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @input="handleReservationTime"
        ></el-date-picker>
      </el-form-item>
    </el-form>
    <el-form :inline="true" label-width="68px">
      <el-form-item label="手机号">
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable></el-input>
      </el-form-item>
      <el-form-item label="预约门诊">
        <el-cascader
          v-model="reservationClinic"
          placeholder="请选择预约门诊"
          clearable
          :options="deptOptions"
          @input="handleReservationClinic"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="跟进人">
        <el-input
          v-model="queryParams.followPerson"
          class="el-input__content"
          placeholder="请输入跟进人"
          clearable
        >
          <el-button slot="append" @click="handleSelectModel">选择</el-button>
        </el-input>
        <select-model
          title="跟进人"
          :show="selectModel.visible"
          @close="handleSelectModel"
          @confirm="handleSelectModelConfirm"
        ></select-model>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <columns-filter-button />
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      border
      stripe
      :data="reservationList"
      :height="clientHeight"
      :max-height="clientHeight"
    >
      <el-table-column width="55" align="center" fixed="left">
        <template slot-scope="scope">
          <el-radio v-model="tableRadio" :label="scope.row">
            <i></i>
          </el-radio>
        </template>
      </el-table-column>
      <columns-filter-view>
        <el-table-column label="预约时间" align="center" prop="reservationTime" width="180">
          <template slot-scope="scope">
            {{
            scope.row.reservationTime &&
            dayjs(scope.row.reservationTime).format('YYYY-MM-DD HH:mm:ss')
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view label="头像">
        <el-table-column label="头像" align="center" prop="imageUrl" :min-width="'头像'">
          <template slot-scope="scope">
            <avatar-image :patient="scope.row" />
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="姓名" align="center" prop="name" min-width="100"></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">{{ sexEnum[scope.row.sex] }}</template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="年龄" align="center" prop="age" />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="手机号" align="center" min-width="180">
          <template slot-scope="scope">
            <hover-phone :type="1" :items="scope.row" />
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="预约项目" align="center" prop="visitDisease" min-width="100" />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="建档人" align="center" prop="filingPerson" min-width="100" />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="跟进人" align="center" prop="followPerson" />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="到店状态" align="center" prop="reachState" />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="预约医生" align="center" prop="reservationDoctor" min-width="100" />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="预约TC" align="center" prop="reservationTc" min-width="100" />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="建档时间" align="center" prop="filingTime" width="180">
          <template slot-scope="scope">
            {{
            scope.row.filingTime &&
            dayjs(scope.row.filingTime).format('YYYY-MM-DD HH:mm:ss')
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="预约门诊" align="center" prop="reservationClinic" min-width="120">
          <template slot-scope="scope">{{ deptEnum[scope.row.reservationClinic] }}</template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="备注"
          align="center"
          prop="remarks"
          min-width="180"
          :show-overflow-tooltip="true"
        />
      </columns-filter-view>
      <empty slot="empty"></empty>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    ></pagination>

    <user-matcher-result contains-temp-clinic-person @update="getList"></user-matcher-result>
    <user-matcher-appointment @submit="getList"></user-matcher-appointment>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { exportReservation, listReservation } from '@/api/services/market'
import { listDept } from '@/api/system/dept'
import { encode, listToTreeOptions } from '@/utils/utils'
import {
  getThisWeekStartWithEnd,
  getTodayStartWithEnd,
  getYesterdayStartWithEnd,
  getThisMonthStartWithEnd,
  formatStartWithEnd,
  getTomorrowStartWithEnd,
  startWithEndMap,
} from '@/utils/date'
import { sexEnum } from '@/utils/enums'

import TablePhone from '@/components/yiya/TablePhone'
import {
  ColumnsFilterButton,
  ColumnsFilterView,
} from '@/components/yiya/TableColumnsFilter'
import SelectModel from '@/components/yiya/showOrHide/selectModel'
import { mapState } from 'vuex'

const QUERY_PARAMS = {
  pageNum: 1,
  pageSize: 50,
  orderByColumn: 'reservationTime',
  isAsc: 'desc',

  startReservationTime: undefined,
  endReservationTime: undefined,
  phoneNumber: undefined,
  reservationClinic: undefined,
  followPerson: undefined,
}

export default {
  name: 'ShopMarket',
  components: {
    Empty: () => import('@/components/yiya/Empty'),
    UserMatcherResult: () => import('@/components/yiya/UserMatcherResult'),
    UserMatcherAppointment: () =>
      import('@/components/yiya/UserMatcherAppointment'),
    HoverPhone: () => import('@/components/yiya/hoverPhone'),
    ColumnsFilterButton,
    ColumnsFilterView,
    SelectModel,
    AvatarImage: () => import('@/components/yiya/avatarImage'),
  },
  data() {
    return {
      loading: true,
      tableRadio: null,
      total: 0,
      reservationList: [],
      queryParams: {},
      deptOptions: [],
      deptEnum: [],
      reservationTime: [],
      reservationClinic: [],
      clientHeight: document.body.clientHeight - 325,
      pickerOptions: {
        firstDayOfWeek: 1,
        shortcuts: [
          {
            text: '今日',
            onClick(picker) {
              const time = getTodayStartWithEnd()
              picker.$emit('pick', time)
            },
          },
          {
            text: '昨日',
            onClick(picker) {
              const time = getYesterdayStartWithEnd()
              picker.$emit('pick', time)
            },
          },
          {
            text: '本周',
            onClick(picker) {
              const time = getThisWeekStartWithEnd()
              picker.$emit('pick', time)
            },
          },
          {
            text: '本月',
            onClick(picker) {
              const time = getThisMonthStartWithEnd()
              picker.$emit('pick', time)
            },
          },
        ],
      },
      selectModel: {
        visible: false,
      },
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
    }),
    dayjs() {
      return dayjs
    },
    sexEnum() {
      return sexEnum
    },
  },
  mounted() {
    this.queryParams = {
      ...QUERY_PARAMS,
      clinicId: +this.clinicId,
    }
    const today = getTodayStartWithEnd()
    this.handleReservationTime(today)
    this.getListDept()
  },
  methods: {
    /**
     * 查询市场建档列表
     */
    async getList() {
      try {
        this.loading = true
        const { rows, total } = await listReservation(this.queryParams)
        this.reservationList = rows
        this.total = total
      } finally {
        this.loading = false
      }
    },
    /**
     * 获取门诊
     */
    async getListDept() {
      const { data } = await listDept()
      const deptEnum = {}
      const options = listToTreeOptions(
        data,
        ({ parentId, deptName, deptId }) => {
          deptEnum[deptId] = deptName
          return {
            parentId,
            id: deptId,
            label: deptName,
            value: deptId,
          }
        }
      )
      this.deptEnum = deptEnum
      this.deptOptions = options[0].children
    },

    /**
     * 搜索按钮操作
     */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /**
     * 重置按钮操作
     */
    resetQuery() {
      this.reservationClinic = []
      this.queryParams.reservationClinic = undefined
      this.queryParams.phoneNumber = undefined
      this.queryParams.followPerson = undefined
      const today = getTodayStartWithEnd()
      this.handleReservationTime(today)
    },

    /**
     * 导出按钮操作
     */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有市场建档数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => exportReservation(queryParams))
        .then((response) => this.download(response.msg))
    },
    /**
     * 点击今日明日本周按钮
     */
    handleDateButtonKeyChange(type) {
      const time = startWithEndMap[type]
      this.handleReservationTime(time)
    },
    /**
     * 改变当前时间
     */
    handleReservationTime(e) {
      const { time, start, end } = formatStartWithEnd(e)
      this.reservationTime = time
      this.queryParams.startReservationTime = start
      this.queryParams.endReservationTime = end
      this.handleQuery()
    },
    handleReservationClinic(e) {
      this.queryParams.reservationClinic = e[1]
    },
    handleSelectModel() {
      this.selectModel = {
        visible: !this.selectModel.visible,
      }
    },
    handleSelectModelConfirm(e) {
      this.handleSelectModel()
      this.queryParams.followPerson = e ? e.userName : undefined
    },
  },
}
</script>

<style lang="scss" scoped>
.el-input__content .el-input-group__append {
  width: 60px;
  background-color: #fff !important;
}
</style>
